<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>优先级队列</title>
</head>
<body>
<script>
    function PriorityQueue() {
        // 可以看成类部类
        function QueueElement(element, priority) {
            this.element = element;
            this.priority = priority;
        }

        //封装属性
        this.items = [];

        //实现插入方法
        PriorityQueue.prototype.enqueue = function (element, priority) {
            // 1.创建QueueElement对象
            let queueElement = new QueueElement(element, priority);

            // 2.判断队列是否为空
            if(this.items.length == 0) {
                this.items.push(queueElement);
            } else {
                let added = false;
                for (let i = 0; i < this.items.length; i++) {
                    if(queueElement.priority < this.items[i].priority) {
                        this.items.splice(i, 0, queueElement);
                        added = true;
                        break;
                    }
                }
                if(!added) {
                    this.items.push(queueElement)
                }
            }
        };

        //2.队列中删除元素
        PriorityQueue.prototype.dequeue = function () {
            return this.item.shift() //移除数组中的第一项并返回该项
        };

        // 3.查看前端元素
        PriorityQueue.prototype.front = function () {
            return this.item[0];
        };

        // 4.查看队列是否为空
        PriorityQueue.prototype.isEmpty = function () {
            return this.item.length == 0
        };

        // 5.查看队列中元素个数
        PriorityQueue.prototype.size = function () {
            return this.item.length
        };

        // 6. toString方法
        PriorityQueue.prototype.toString = function () {
            let resultString = '';
            for(let i = 0; i < this.items.length; i++) {
                let p = this.items[i];
                resultString += p.element + '-' + p.priority + ' '
            }
            return resultString
        };

    }
    //测试代码
    let pq = new PriorityQueue();

    pq.enqueue('进击的巨人', 1);
    pq.enqueue('钢之炼金术师', 3);
    pq.enqueue('寄生兽', 2);
    pq.enqueue('家有女友', 4);

    alert(pq);
</script>
</body>
</html>